#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <uuid/uuid.h>



/**
* [root@localhost test]# echo "obase=2 ; ibase=16 ; B560BA196D3C63CACF550D0F0FE7E137"  | bc  
10110101011000001011101000011001011011010011110001100011110010101100\
111101010101000011010000111100001111111001111110000100110111

2556d237-ab7b-499e-9cda-796ed252810d
*/

char * generte_uuid()
{
  uuid_t uuid;
  uuid_generate(uuid);
  char *uuid_str = (char*)malloc(37);
  if(!uuid_str) return NULL;
  memset(uuid_str,0,37);
  uuid_unparse(uuid,uuid_str);
  uuid_clear(uuid);
  int i;
  for(i=0;i<36;i++){
    char *c = uuid_str + i;
    char *n = uuid_str + i + 1;
    if( *c != '-') continue;
    *c = 0;
    while(*n){
      char s = *c;
      *c = *n;
      *n = s;
      n++;
      c++;
    }
  }
  return uuid_str;
}

char * tobase64(char *buf,int len)
{
  static char   basis64[] =
    		"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  //char *res = (char*)malloc(len+1);
  //memset(res,0,len+1);
  int i = 0;
  for(;i<len;i++){
     char c = buf[i];
     //res[i] = basis64[c&0x3F]; 
     buf[i] = basis64[c&0x3F]; 
  }
  //printf("%s\n",buf);
  return buf;
}

char * create_short_url()
{
  char     *str = generte_uuid();
  if(!str) return NULL;
  char     *buf = (char*)malloc(7);
  if(!buf){
     return NULL;
  }
  u_int8_t len  = strlen(str);
  int i,j=0,bi=0;
  for(i=0;i<len;i=i+2,j++){
    if(j%2 == 0){
      continue;
    }
    char *b = str + i; 
    char *e = str + i + 2; 
    char o  = *e;
    *e = 0;
    int ai = (int)strtoul(b,(char**)NULL,16);
    buf[bi++] = (char)ai;
    //printf("%s %d %d\n",b,ai,buf[bi-1]);
    *e = o;
    if(bi==6) break;
  }
  free(str); 
  tobase64(buf,6);
  //printf("%s\n",buf);
  return buf;
}

u_int64_t parseShortUrl(char *str)
{
  int  i;
  u_int64_t ret = 0;
  u_int8_t  len = strlen(str);
  for(i=0;i<len;i++){
    char c = str[i];
    ret = (ret<<8) | c; 
    //printf("%c %d %llu\n",c,sizeof(u_int64_t),ret);
  } 
  return ret;
}

int main(int argc , char *argv[])
{

   char *p = create_short_url(); 
   //printf("%s\n",p);
   u_int64_t ll = parseShortUrl(p); 
   free(p);
   printf("%llu\n",ll);
   ll = parseShortUrl(argv[1]);
   printf("%llu\n",ll);
   return 0;
}
